#!/bin/sh /etc/rc.common

# Startup script for running a system-wide instance of the pitsd daemon.

# Copyright (c) 2011 The Chromium Authors. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
#
# Author: Markus Gutschke

START=50

CFG=/tmp/.pitsd
SHADOW=/etc/pitsd.conf
DAEMON=/bin/pitsd

[ -x "${DAEMON}" ] || exit 0
[ -r "${SHADOW}" ] || exit 0

daemon() {
  local pid
  pid=`sed 's/^ *"daemon": "\([0-9]*\).*/\1/
            t1
            d
            :1
            q' "${CFG}" 2>/dev/null || :`
  if [ -n "${pid}" ]; then
    kill -0 "${pid}" >/dev/null 2>&1 || pid=
  fi
  echo "${pid}"
}

start() {
  [ -n "`daemon`" ] && return || :
  cp "${SHADOW}" "${CFG}"
  cd "`dirname "${CFG}"`"
  ( set +e
    while :; do
      [ -n "`daemon`" ] && exit 0
      "${DAEMON}" >/dev/null 2>&1
      [ $? -eq 137 ] && exit 0
      [ -n "`daemon`" ] && exit 0
      sleep 5
    done) </dev/null >/dev/null 2>&1 &
  for i in 1 2 3; do
    [ -n "`daemon`" ] && return || :
    sleep 1
  done
}

stop() {
  local pid
  pid="`daemon`"
  [ -n "${pid}" ] && kill -9 "${pid}" >/dev/null 2>&1 || :
  for i in 1 2 3; do
    [ -z "`daemon`" ] && return || :
    sleep 1
  done
}

reload() {
  restart
}
